package com.ego.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ego.admin.dao.SysAdminDao;
import com.ego.admin.po.SysAdmin;
import com.ego.admin.po.SysMenu;
import com.ego.admin.service.SysAdminRoleService;
import com.ego.admin.service.SysAdminService;
import com.ego.admin.service.SysMenuService;
import com.ego.admin.vo.SysUserSearchVo;
import com.ego.common.constant.SystemConstant;
import com.ego.common.exception.GlobalException;
import com.ego.common.util.PageUtil;
import com.ego.common.vo.PageVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: ego
 * @description:
 * @author: KamTang
 * @create: 2022-11-11 11:31
 **/
@Service("sysAdminService")
public class SysAdminServiceImpl extends ServiceImpl<SysAdminDao, SysAdmin> implements SysAdminService {

    @Autowired
    private SysAdminRoleService adminRoleService;
    @Autowired
    @Lazy
    private SysMenuService menuService;

    @Override
    public SysAdmin queryByUserName(String username) {
        return this.baseMapper.get(username);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public PageVo<SysAdmin> search(SysUserSearchVo search) {
        search.setPageNum(search.getPageNum() - 1);
        List<SysAdmin> admins = baseMapper.search(search);
        Page<SysAdmin> page = baseMapper.selectPage(Page.of(search.getPageNum(), search.getPageSize()), null);
        return PageUtil.toPage(page, admins);
    }

    @Override
    public int countPeopleByDepartmentId(Long departmentId) {
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<SysAdmin>().eq("department_id", departmentId);
        return this.baseMapper.selectCount(wrapper).intValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysAdmin admin) {
        // 判断是否存在重名
        SysAdmin userName = queryByUserName(admin.getUsername());
        if (userName != null) {
            throw new GlobalException("该用户名已存在，请重新输入", 500);
        } else {
            // 256加密
            String salt = RandomStringUtils.randomAlphabetic(20);
            admin.setSalt(salt);
            admin.setPassword(new Sha256Hash(admin.getPassword(), salt).toHex());
            this.save(admin);

            // 保存用户与角色关系
            adminRoleService.saveOrUpdate(admin.getUserId(), admin.getRoleIdList());
        }
    }

    @Override
    public void update(SysAdmin admin) {
        if (StringUtils.isBlank(admin.getPassword())) {
            admin.setPassword(null);
        } else {
            admin.setPassword(new Sha256Hash(admin.getPassword(), admin.getSalt()).toHex());
        }
        this.updateById(admin);

        //保存用户与角色关系
        adminRoleService.saveOrUpdate(admin.getUserId(), admin.getRoleIdList());
    }

    @Override
    public List<String> getAllPermsById(Long userId) {
        return this.baseMapper.getAllPermsById(userId);
    }

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;
        if (userId == SystemConstant.UserEnum.SUPER_ADMIN.getCode()) {
            List<SysMenu> menuList = menuService.list();
            permsList = new ArrayList<>(menuList.size());
            for (SysMenu menu : menuList
            ) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = getAllPermsById(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            // 去掉空值
            if (org.apache.commons.lang.StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public List<Long> getMenuIdByUserId(Long userId) {
        return this.baseMapper.queryAllMenuId(userId);
    }

    @Override
    public boolean updatePwd(Long userId, String password, String newPassword) {
        SysAdmin admin = new SysAdmin();
        admin.setPassword(newPassword);
        return this.update(admin, new QueryWrapper<SysAdmin>().eq("user_id", userId).eq("password", password));
    }
}
